package com.analysis.apresunday.service.impl;

import com.analysis.apresunday.config.ResultCode;
import com.analysis.apresunday.config.ScriptConfig;
import com.analysis.apresunday.config.exception.GlobalException;
import com.analysis.apresunday.entity.dto.EmpDataPageDTO;
import com.analysis.apresunday.entity.po.EmpData;
import com.analysis.apresunday.mapper.EmpDataMapper;
import com.analysis.apresunday.service.EmpDataService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Service
@Slf4j
public class EmpDataServiceImpl extends ServiceImpl<EmpDataMapper, EmpData> implements EmpDataService {
    @Resource
    EmpDataMapper empDataMapper;

    @Resource
    ScriptConfig scriptConfig;

    @Override
    public IPage<EmpData> getPageList(EmpDataPageDTO req, HttpServletRequest request) {
        // 创建分页对象，使用 MyBatis Plus 的 Page 类
        Page<EmpData> page = new Page<>(req.getCurrent(), req.getSize());

        // 构造查询条件
        QueryWrapper<EmpData> query = new QueryWrapper<>();

        if (!StringUtils.isEmpty(req.getPosition())) {
            query.like("position", req.getPosition());
        }

        // 工作经验
        if (!StringUtils.isEmpty(req.getExperience())) {
            query.eq("experience", req.getExperience());
        }

        // 薪资范围
        if (!StringUtils.isEmpty(req.getSalary())) {
            String[] split = req.getSalary().split("-");
            if (split.length == 2) {
                query.between("min_salary", Integer.parseInt(split[0]), Integer.parseInt(split[1]));
            } else {
                query.ge("min_salary", Integer.parseInt(split[0]));
            }
        }

        // 学历要求
        if (!StringUtils.isEmpty(req.getEducation())) {
            query.eq("education", req.getEducation());
        }

        // 城市
        String city;
        if (!StringUtils.isEmpty(req.getCity())) {
            String[] split = req.getCity().split("-");
            if (split.length == 2) {
                if (!split[1].equals("市辖区")) {
                    city = split[1];
                    String substring = city.substring(0, city.length() - 1);
                    query.eq("city", substring);
                } else {
                    city = split[0];
                    String substring = city.substring(0, city.length() - 1);
                    query.eq("city", substring);
                }
            }
        }

        // 岗位分类
        if (!StringUtils.isEmpty(req.getClassify())) {
            query.eq("classify", req.getClassify());
        }

        // 使用 MyBatis Plus 的 selectPage 方法进行分页查询
        return empDataMapper.selectPage(page, query);
    }


    @Override
    public String getEmpUrl(String keyword) {
        // 生成时间戳
        long timestamp = System.currentTimeMillis() / 1000 - 60;

        // 对用户输入进行编码
        String encodedKeyword;
        try {
            encodedKeyword = URLEncoder.encode(keyword, StandardCharsets.UTF_8.toString());
        } catch (Exception e) {
            e.printStackTrace();
            return null; // 如果编码失败，返回 null
        }

        // 生成URL
        return String.format("https://we.51job.com/api/job/search-pc?api_key=51job&timestamp=%d&keyword=%s&searchType=2&function=&industry=&jobArea=000000&jobArea2=&landmark=&metro=&salary=&workYear=&degree=&companyType=&companySize=&jobType=&issueDate=&sortType=0&requestId=&source=1&accountId=&pageCode=sou%%7Csou%%7Csoulb",
                timestamp, encodedKeyword);
    }

    @Override
    public boolean executeAutoCrawlScript(String keyword) {
        log.info("开始脚本执行流程，关键字:{}", keyword);
        // 执行脚本执行数据处理流程
        try {
            // Python 脚本路径
            String pythonScriptPath = scriptConfig.getPath() + scriptConfig.getWashDataPath();

            // 构建 ProcessBuilder
            ProcessBuilder processBuilder = new ProcessBuilder(scriptConfig.getPythonExePath(), pythonScriptPath, keyword, scriptConfig.getPath());

            // 启动进程
            Process process = processBuilder.start();

            // 获取脚本的标准输出流
            InputStream inputStream = process.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));

            // 保存输出
            StringBuilder outputBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                outputBuilder.append(line).append("\n");
            }

            // 输出完整结果
            String fullOutput = outputBuilder.toString();
            log.info("输出python完整结果：\n{}", fullOutput);

            // 如果 fullOutput 包含 "Could not reach host"，返回 false
            if (fullOutput.contains("程序执行时出错")) {
                log.error("检测到程序执行时出错");
                return false;
            }

            // 获取脚本的标准错误流
            InputStream errorStream = process.getErrorStream();
            BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream));

            // 保存错误输出
            StringBuilder errorOutputBuilder = new StringBuilder();
            while ((line = errorReader.readLine()) != null) {
                errorOutputBuilder.append(line).append("\n");
            }

            // 输出错误信息
            String errorOutput = errorOutputBuilder.toString();
            if (!errorOutput.isEmpty()) {
                log.error("Error output:\n {}", errorOutput);
                throw new GlobalException(ResultCode.ERROR, "执行脚本过程出现错误！");
            }

            // 等待脚本执行完成
            int exitCode = process.waitFor();
            log.info("Python script exited with code: {}", exitCode);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            throw new GlobalException(ResultCode.ERROR, "执行脚本过程出现错误！");
        }
        return true; // 如果没有遇到错误，返回 true
    }


}
